package top.huntwolf.admin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.BeanUtils;
import top.huntwolf.admin.common.enums.BookConditionEnum;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.pojo.BookReserve;
import top.huntwolf.admin.pojo.Subject;
import top.huntwolf.admin.pojo.book.BuyBook;
import top.huntwolf.admin.pojo.excel.BookExcelData;
import top.huntwolf.admin.service.BookService;
import top.huntwolf.admin.service.BookReserveService;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BookExcelListener extends AnalysisEventListener<BookExcelData> {

    private BookService bookService;

    private BookReserveService conditionService;

    public BookExcelListener() {

    }

    public BookExcelListener(BookService bookService, BookReserveService conditionService) {
        this.bookService = bookService;
        this.conditionService = conditionService;
    }


    // 每执行一行都会调用该方法
    @Override
    public void invoke(BookExcelData bookExcelData, AnalysisContext analysisContext) {
        if (bookExcelData == null) {
            throw new ServiceException(CodeMsg.READ_EXCEL_ERROR);
        }
        // 1、判断该课本是否存在
        BuyBook book = this.exist(bookExcelData.getIsbn().trim());

        // 1.1存在跳过
        if (book == null) {
            book = new BuyBook();
            // 1.2不存在才执行下面的语句
            // 根据所属的一、二级分类名称找到subjectId和subjectParentId
            // 先找二级分类
            Subject subject = this.getBookSubjectId(bookExcelData.getSubjectId());
            // 用beanUtils赋值Book
            BeanUtils.copyProperties(bookExcelData, book);
            // 填充Excel表中没有的字段
            book = this.completeBook(book);
            // 添加分类
//            book.setSubjectId(subject.getId());
//            book.setSubjectParentId(subject.getParentId());
            // 插入到数据库中去
            bookService.insert(book);
        }
        //插入折扣表
        BookReserve bookCondition = new BookReserve();
        bookCondition.setIsbn(bookExcelData.getIsbn().trim());
        String[] sellingPrice = getPrice(bookExcelData.getSellingPrice());
        if(sellingPrice[0]==null){
            bookCondition.setDiscount("0.40");
        }else {
            bookCondition.setDiscount(sellingPrice[0]);
        }
        if(sellingPrice[1]==null){
            bookCondition.setRealPrice("0.00");
        }else {
            bookCondition.setRealPrice(sellingPrice[1]);
        }
        if(bookExcelData.getStorage()==null){
            bookCondition.setStorage(0);
        }else {
            bookCondition.setStorage(Integer.parseInt(bookExcelData.getStorage()));
        }
        bookCondition.setConditionEnum(BookConditionEnum.MEDIUM);
        conditionService.replace(bookCondition);

    }

    public String[] getPrice(String input)
    {

        if(input==null)
            return new String[2];
        Pattern p = Pattern.compile("\\s*(\\d[\\.\\d]*\\d*)");
        Matcher m = p.matcher(input);
        boolean result = m.find();
        String[] find_result = new String[2];
        if (result)
        {
            find_result[0] = String.format("%.2f",m.group(1).length() >= 2 ? Double.parseDouble(m.group()) * 0.01 : Double.parseDouble(m.group()) * 0.1);
            m.find();
            find_result[1] = m.group(1);
        }
        return find_result;
    }

    private Subject getBookSubjectId(String subjectId) {
        return bookService.findSubjectByTitle(subjectId);
    }

    // 填充excel表中缺失字段
    private BuyBook completeBook(BuyBook book) {
        // 获取易源的book实体
        BuyBook bookDetailsFromApi = bookService.getBookDetailsFromApi(book.getIsbn());
        String apiBookString = JSONObject.toJSONString(bookDetailsFromApi);
        String bookString = JSONObject.toJSONString(book,SerializerFeature.WriteMapNullValue);


        Map<String, Object> bookMap = JSONObject.parseObject(bookString,new TypeReference<Map<String, Object>>() {
        });
        Map<String, Object> apiBookMap = JSONObject.parseObject(apiBookString, Map.class);

        // 实现如果excel表中无数据，自动从易源中获取
        for (Map.Entry<String, Object> entry : bookMap.entrySet()) {
            String key = entry.getKey();
            if (entry.getValue() == null && apiBookMap.containsKey(key)) {

                entry.setValue(apiBookMap.get(key));
            }
        }
        // 将封装好的bookMap转换成字符串再转成对象返回
        String completedBookString = JSONObject.toJSONString(bookMap);
        BuyBook completedBook = JSONObject.parseObject(completedBookString, BuyBook.class);
        return completedBook;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public BuyBook exist(String isbn) {
        return bookService.DirectQueryBookFromDataBase(isbn);
    }
}
